package com.weixing.mall.provider.controller.front;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.enums.ResultCodeEnum;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.core.annotation.NoNeedAccess;
import com.weixing.mall.core.properties.WeiXingProperties;
import com.weixing.mall.core.support.BaseController;
import com.weixing.mall.core.support.ImageService;
import com.weixing.mall.core.support.auth.AuthUtil;
import com.weixing.mall.core.support.auth.MemAuth;
import com.weixing.mall.core.support.auth.MemInfo;
import com.weixing.mall.core.support.imgsearch.ImgSearchAddDto;
import com.weixing.mall.provider.api.model.vo.ActRpcVo;
import com.weixing.mall.provider.api.service.ActivityRpcService;
import com.weixing.mall.provider.mapper.GoodsMapper;
import com.weixing.mall.provider.model.domain.GoodsVisit;
import com.weixing.mall.provider.model.domain.Product;
import com.weixing.mall.provider.model.query.CategoryQuery;
import com.weixing.mall.provider.model.query.FrontGoodsQuery;
import com.weixing.mall.provider.model.query.HotGoodsQuery;
import com.weixing.mall.provider.model.vo.SkuVo;
import com.weixing.mall.provider.model.vo.SpuVo;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.provider.service.impl.QueryCriteriaImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 前端:商品Api
 *
 * @author  Small
 * @date  2019/11/5 18:05
 * @since  1.0
 **/
@RestController
@RequestMapping("front/goods")
@Api(value = "前端:商品Api", tags = "前端:商品")
public class FrontGoodsController extends BaseController {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private QueryCriteriaImpl queryCriteriaImpl;

    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private ICategoryService categoryService;
    @Autowired
    private IGoodsVisitService goodsVisitService;
    @Resource
    private TaskExecutor taskExecutor;

    @Autowired
    private IProductService productService;

   @Autowired
   private ActivityRpcService activityRpcService;
    @Autowired
    private WeiXingProperties weiXingProperties;

    @ApiOperation(value = "商品详情")
    @GetMapping(value = "{id}")
    @NoNeedAccess
    public Result<SpuVo> item(@PathVariable Long id) {
        //加载数据
        MemAuth memberExt = AuthUtil.getMemberExt();
        Long mid = null == memberExt ? null : memberExt.getMid();
        SpuVo spuVo = this.goodsService.loadModel(id, null, mid);
        if (null != memberExt) {
            spuVo.setAf(memberExt.getAf());
        }
//        taskExecutor.execute(() -> this.createVisit(auth,id));
        return ResultUtil.success(spuVo);
    }

    /**
     *   根据货品ID获取商品的SKU列表
     * @param id
     * @return
     */
    @ApiOperation(value = "根据productId获取商品详情")
    @GetMapping(value = "/skuList/{id}")
    @NoNeedAccess
    public Result skuList(@PathVariable Long id,Long actId) {
        List<SkuVo>  skuVoList=null;
        if(ObjectUtil.isNull(actId)){
            skuVoList= goodsService.skuList(id);
        }else{
            try{
                ActRpcVo actRpcVo= activityRpcService.selectById(actId).getData();
                if( actRpcVo.getEndTime().getTime()-new Date().getTime()<0){
                    return ResultUtil.success(ResultCodeEnum.ERROR,"活动已经结束");
                }

            }catch (Exception e){

            }

            skuVoList= goodsService.skuList(id,actId);
        }

        return ResultUtil.success(skuVoList);
    }

    @ApiOperation(value = "根据goodsSn去查找商品")
    @GetMapping(value = "goodsSn/{goodsSn}")
    @NoNeedAccess
    public Result<SpuVo> loadItemByGoosSn(@MemInfo MemAuth auth, @PathVariable String goodsSn) {
        //加载数据
        //SpuVo spuVo = goodsService.loadModelByGoodsSn(initMpPage(), goodsSn);
        //return ResultUtil.success(spuVo);
        return ResultUtil.success();
    }


    private void createVisit(MemAuth auth, @PathVariable Long id) {
        if (null != auth) {
            GoodsVisit visit = new GoodsVisit();
            visit.setGoodsId(id);
            visit.setMemberId(auth.getMid());
            goodsVisitService.save(visit);
        }
    }

    @ApiOperation(value = "活动商品详情")
    @GetMapping(value = "{id}/{actId}")
    @NoNeedAccess
    public Result<SpuVo> itemAct(@PathVariable("id") Long id, @PathVariable("actId") Long actId) {
        //加载数据
        MemAuth memberExt = AuthUtil.getMemberExt();
        Long mid = null == memberExt ? null : memberExt.getMid();
        SpuVo spuVo = this.goodsService.loadModel(id, actId, mid);
        if (null != memberExt) {
            spuVo.setAf(memberExt.getAf());
        }
        return ResultUtil.success(spuVo);
    }

    @ApiOperation(value = "商品搜索")
    @GetMapping("getList")
    @NoNeedAccess
    public Result getList(FrontGoodsQuery frontGoodsQuery) {
        return ResultUtil.success(goodsService.selectFrontGoods(initMpPage(), frontGoodsQuery));
    }

    @ApiOperation(value = "活动商品搜索")
    @GetMapping("getActList")
    @NoNeedAccess
    public Result getActList(FrontGoodsQuery frontGoodsQuery) {
        return ResultUtil.success(goodsService.selectActFrontGoods(initMpPage(), frontGoodsQuery));
    }

    /**
     * 前端图片搜搜服务
     * @param file  搜索的图片文件流
     * @param pageSize  页码
     * @param actId  活动Id
     * @return
     */
    @ApiOperation(value = "图片商品搜索")
    @PostMapping("getImgList")
    @NoNeedAccess
    public Result getImgList(MultipartFile file,Integer pageSize,Long actId) {
        return ResultUtil.success(goodsService.imgSerchList( file,pageSize,actId));
    }

    /**
     * 前端图片搜搜服务测试

     * @return
     */
    @ApiOperation(value = "图片商品搜索")
    @PostMapping("getImgAddList")
    @NoNeedAccess
    public Result getImgAddList() {
        List<ImgSearchAddDto> imgSearchAddDtos= Lists.newArrayList();
        List<Product> productList=productService.list(new QueryWrapper<Product>().eq("goods_id",97504));
        for(Product product:productList){
            ImgSearchAddDto dto=new ImgSearchAddDto();
            dto.setImgUrl(GlobalConstant.IMG_PATH_URL+product.getProductImg());
            dto.setProductId(product.getId().toString()+","+product.getId());
            dto.setPicName(product.getProductName()+","+GlobalConstant.IMG_PATH_URL+product.getProductImg());
            dto.setStrAttr(product.getDiscountPrice()+","+product.getMarketPrice());
            dto.setCustomContent(product.getStyleNo());

            imgSearchAddDtos.add(dto);
            try {
                ImageService imageService=new ImageService();
                imageService.add(imgSearchAddDtos,weiXingProperties.getAli().getImg());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ResultUtil.success();
    }
    @ApiOperation(value = "热销商品")
    @GetMapping("hotGoods")
    @NoNeedAccess
    public Result hotGoods(HotGoodsQuery hotGoodsQuery) {
        return ResultUtil.success(goodsService.hotGoods(initMpPage(), hotGoodsQuery));
    }

    @ApiOperation(value = "活动热销商品(废除)")
    @GetMapping("actHotGoods")
    @NoNeedAccess
    public Result actHotGoods(HotGoodsQuery hotGoodsQuery) {
        return ResultUtil.success(goodsMapper.actHotGoods(initMpPage(), hotGoodsQuery));
    }

    @ApiOperation(value = "商品分类（根据条件加载商品类目(默认后台用的是可用了类目)）")
    @GetMapping("getGoodsCategory")
    @NoNeedAccess
    public Result getGoodsCategory(CategoryQuery categoryQuery) {
        return ResultUtil.success(categoryService.selectList(categoryQuery));
    }

    @ApiOperation(value = "商品搜索条件")
    @GetMapping("queryCriteria")
    @NoNeedAccess
    public Result queryCriteria() {
        return ResultUtil.success(queryCriteriaImpl.initQueryCriteria());
    }


    @ApiOperation(value = "商品分类id加载商品列表")
    @GetMapping("getListByCategoryId/{categoryId}")
    @NoNeedAccess
    public Result getListByCategoryId(@PathVariable Long categoryId) {
        FrontGoodsQuery frontGoodsQuery = new FrontGoodsQuery();
        frontGoodsQuery.setCatlevel2Id(categoryId);
        return ResultUtil.success(goodsService.selectFrontGoods(initMpPage(), frontGoodsQuery));
    }

    @ApiOperation(value = "根据商品ID获取颜色和尺码集合")
    @GetMapping("getSkuListByGoodId/{goodId}")
    @NoNeedAccess
    public Result getSkuListByGoodId(@PathVariable Long goodId) {
        Map<String, List<SkuVo>> result=productService.getSkuListByGoodId(goodId);
        return ResultUtil.success(result);
    }

}
